from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from mall import settings
from mall.settings import QQ_CLIENT_ID, QQ_CLIENT_SECRET, QQ_REDIRECT_URI
from oauth.models import OAuthQQUser
from oauth.serializers import QQAuthUserSerializer
from oauth.utils import generic_access_token
from utils.constants import TOKEN_EXPIRE


class QQAuthUSERView(APIView):

    """
    请求方式:   GET
    请求路径:   /oauth/qq/statues/?state=xxx
    用户点qq登录,发送ajax请求到后台,后台返回一个qq登录的网址

    """
    def get(self, request):
        state = request.query_params.get("state")
        if not state:
            state = "/"
        oauth = OAuthQQ(
            client_id=QQ_CLIENT_ID,
            client_secret=QQ_CLIENT_SECRET,
            redirect_uri=QQ_REDIRECT_URI,
            state=state
        )
        url = oauth.get_qq_url()
        return Response({'login_url': url})

class QQAuthUserView(APIView):
    """
    GET /oauth/qq/users/?code=xxx
    """
    def get(self, request):

        code = request.query_params.get("code")
        if not code:
            return Response({"message": "缺少code"}, status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ(
            client_id=QQ_CLIENT_ID,
            client_secret=QQ_CLIENT_SECRET,
            redirect_uri=QQ_REDIRECT_URI
        )
        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)
        except Exception:
            return Response({"message": "QQ服务器异常", }, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # return openid
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城用户，创建用户并绑定到openid
            # 为了能够在后续的绑定用户操作中前端可以使用openid，在这里将openid签名后响应给前端
            # 对openid进行一个加密处理
            access_token = generic_access_token(openid)

            return Response({
                "access_token": access_token
            })
            pass
        else:

            # 手动创建一个令牌
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(oauth_user)
            token = jwt_encode_handler(payload)

            # 说明用户登录成功了,登录成功的话,就应该给他返回一个token
            return Response({
                "token": token,
                "username": oauth_user.user.username,
                "user_id": oauth_user.user.id,
            })

        # finally:
        #     pass


    def post(self, request):
        """
        用户绑定完信息之后,前端应该将手机号,密码,短信验证码,以及处理之后的openid传递过去
        1.接收参数
        2.校验(短信验证码,openid,根据手机号,查询这个用户是否存在)
        3.保存数据
        4.返回响应
        """
        data = request.data
        serializer = QQAuthUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        qquser = serializer.save()

        # 手动创建新令牌,有时您可能希望手动生成令牌，例如在创建帐户后立即将令牌返回给用户。你可以这样做：

        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)

        return Response({
            "token": token,
            "username": qquser.user.username,
            "user_id": qquser.user.id
        })

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
"""
1.创建序列化器,2.组织数据,3.加密,4.解密
"""
# serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=TOKEN_EXPIRE)
# data = {"openid":1234567890}
# token = serializer.dumps(data)
# serializer.loads(token)

# OAuthWX
# class WXAuthUSERView(APIView):
#
#     login_url = ""



